// 1. 引入
import { createRouter, createWebHashHistory, useRouter } from "vue-router"

import Home from '@/view/Home.vue'
import Login from '@/view/Login.vue'
import NotFound from '@/view/NotFound.vue'
import Admin from '@/layout/Admin.vue'
import list from '@/view/goods/list.vue'
import listimg from "@/view/image/list.vue"
import { getcookies } from "@/utils/cookies.js";
import { toast } from "@/utils/toast.js";
// import { useStore } from "vuex"
// const store = useStore()

import store from "../store"
// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
const routes = [
  {
    path: '/', component: Admin, meta: {
      title: "秒杀后台的管理首页"
    },
    children: [
      {
        path: '/', component: Home,
        meta: {
          title: "秒杀后台的管理首页"
        }
      },
      {
        path: '/goods/list', component: list,
         meta: {
          title: "秒杀后台的商品管理首页"
        },
      },
      {
        path: '/image/list', component: listimg,
         meta: {
          title: "秒杀后台的照片管理首页"
        },
      },
    ]
  },
  {
    path: '/Login', component: Login, meta: {
      title: "秒杀后台的管理登录页",
      icon: "https://c-ssl.duitang.com/uploads/item/202005/31/20200531230656_cXMfF.jpeg"
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: "从未见过如此厚颜无耻之页"
    }
  },
]

// 3. 创建路由实例并传递 `routes` 配置
const router = createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
  history: createWebHashHistory(),
  routes, // `routes: routes` 的缩写
})

router.beforeEach((to, from, next) => {
  let token = getcookies("user-token")
  if (!token && to.path !== "/Login") {
    toast('您未登录，请先登录', "", "", "info")
    next({ path: '/Login' })
  }
  if (token && to.path === "/Login") {
    toast('已登录，请勿重复登录', "", "", "info")
    next({ path: from.path })
  }
  if (token) {
    store.dispatch('actionsSetuserinfo')
  }

  document.title = to.meta.title

  next()
})


export default router